const jwt = require('koa-jwt');
const { jwtSecret } = require('./index');
const User = require('@root/models/user.model');
const passport = require('koa-passport');



const authenticate = strategy => async (ctx, next) => {
  
  return passport.authenticate(strategy,async(err, user,info) => {
  
    // const auser = await User.findOne({'local.email':'test1@qq.com'});
    // return ctx.body = auser;
    if (err) {
      // return ctx.throw(500, err);
      return (ctx.body = {
        code: 500,
        mssage: '服务器错误',
        err
      });
    }

    // If there were no errors and no user was retrieved, it's an
    // authentication issue. i.e., HTTP 401 Unauthorized.
    if (!user) {
      // return ctx.throw(401, err);
      return (ctx.body = {
        code: 401,
        mssage: '邮箱或者密码错误',
        err
      });
    }
    console.log('user---',user)
    console.log('info---',info)
    ctx.body = { user: user.toAuthJSON() };
  })(ctx,next)

};

const authJWT = {
  required: jwt({
    secret: jwtSecret
  }),
  optional: jwt({
    secret: jwtSecret,
    passthrough: true
  })
};

module.exports = {
  authenticate,
  authJWT
};
